import React, { useState, useEffect, useCallback } from 'react';
import { Upload, message, Spin } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

/**
 * 图片上传组件
 * 用于上传场地图片
 * @param {Object} props
 * @param {Array|String} props.value - 当前图片URL列表或JSON字符串
 * @param {Function} props.onChange - 值变化回调
 * @param {Boolean} props.multiple - 是否支持多图上传
 */
const ImageUploader = ({ value = [], onChange, multiple = false }) => {
  const [loading, setLoading] = useState(false);
  const [headers, setHeaders] = useState({});
  const [imageUrls, setImageUrls] = useState([]);

  // 初始化图片列表
  useEffect(() => {
    if (Array.isArray(value)) {
      setImageUrls(value);
    } else if (typeof value === 'string' && value) {
      try {
        // 尝试解析JSON字符串
        const parsedValue = JSON.parse(value);
        setImageUrls(Array.isArray(parsedValue) ? parsedValue : []);
      } catch (error) {
        // 如果不是JSON格式，可能是单个URL
        setImageUrls(value ? [value] : []);
        console.error('解析图片数据失败:', error);
      }
    } else {
      setImageUrls([]);
    }
  }, [JSON.stringify(value)]);

  // 处理图片变化
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
  };

  // 处理图片移除
  const handleRemove = useCallback((file) => {
    const index = imageUrls.indexOf(file.url);
    if (index !== -1) {
      const newImageUrls = [...imageUrls];
      newImageUrls.splice(index, 1);
      setImageUrls(newImageUrls);
      onChange(multiple ? JSON.stringify(newImageUrls) : (newImageUrls.length > 0 ? newImageUrls[0] : ''));
    }
  }, [imageUrls, onChange, multiple]);

  // 自定义上传请求
  const customRequest = useCallback(async ({ file, onSuccess, onError }) => {
    try {
      const formData = new FormData();
      const fieldName = multiple ? 'files' : 'file';
      formData.append(fieldName, file);

      const url = multiple ? '/api/v1/upload/multi' : '/api/v1/upload';
      const res = await fetch(url, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        },
        body: formData
      });

      const data = await res.json();

      if (data.success) {
        setLoading(false);
        let urls = [];
        
        if (multiple) {
          // 多图上传返回数组
          urls = data.data || [];
          const newImageUrls = [...imageUrls, ...urls];
          setImageUrls(newImageUrls);
          onChange(JSON.stringify(newImageUrls));
        } else {
          // 单图上传返回单个URL
          const url = data.data;
          if (url) {
            setImageUrls([url]);
            onChange(url);
          }
        }
      } else {
        message.error('上传失败，请重试：' + data.message);
      }

      // 构造符合组件要求的响应对象
      onSuccess({
        status: 'success',
        url: data.data,
        response: data
      }, file);
    } catch (err) {
      onError(err);
    }
  }, [imageUrls, onChange, multiple]);

  // 上传前检查
  const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件');
    }
    const token = localStorage.getItem('token');
    const authHeader = { Authorization: 'Bearer ' + token };
    setHeaders(authHeader);
    return isImage;
  };

  return (
    <Upload
      listType="picture-card"
      action={multiple ? '/api/v1/upload/multi' : '/api/v1/upload'}
      beforeUpload={beforeUpload}
      customRequest={customRequest}
      onChange={handleChange}
      headers={headers}
      maxCount={multiple ? 5 : 1}
      showUploadList={{ showPreviewIcon: false }}
      disabled={loading}
      fileList={imageUrls.map(url => ({ url }))}
      onRemove={handleRemove}
    >
      {(!multiple && imageUrls.length > 0) ? null : (loading ? <Spin /> : <PlusOutlined />)}
    </Upload>
  );
};

export default ImageUploader;